package cn.tsmchina.one.controller.category;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.tsmchina.one.domain.category.Category;
import cn.tsmchina.one.domain.product.Product;
import cn.tsmchina.one.pojo.RestaurantPojo;
import cn.tsmchina.one.service.category.CategoryService;
import cn.tsmchina.one.service.product.ProductService;
import cn.tsmchina.one.service.user.CustomerService;
import cn.tsmchina.one.util.C;
import cn.tsmchina.one.util.JsonUtil;
import cn.tsmchina.one.util.LoginUtil;

@Controller
@RequestMapping("/category")
public class CategoryController
{
	@Autowired
	private CategoryService categoryService;
	
	@Autowired
	private ProductService productService;
	@Autowired
	private CustomerService customerService;
	/**
	 * 店铺列表信息查询
	 * @param model
	 * @return
	 */
	@RequestMapping("/details/{id}")
	public String activity(@PathVariable("id") int id, Model model, HttpServletRequest request)
	{
		request.getSession().setAttribute("currentRestaurantId", id);//切换店铺的时候保存当前店铺的id
		Category restaurant = categoryService.getById(id);
//		request.setAttribute("restaurant", restaurant);
		restaurant(restaurant, model);
		return "m/restaurantDetails";
	}
	
	/**
	 * 店铺详情
	 * @param model
	 * @return
	 */
	@RequestMapping("/rquery/{id}")
	public String activityDetail(@PathVariable("id")int id,HttpServletRequest request)
	{
		return "activityDetail";
	}
	
	@InitBinder
	public void convertDate(WebDataBinder binder)
	{
		CustomDateEditor editor = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false);
		binder.registerCustomEditor(Date.class,editor);
	}
	
	private void restaurant(Category restaurant, Model model)
	{
		RestaurantPojo restaurantPojo = JsonUtil.parseObject(RestaurantPojo.class, restaurant.getParams());
		restaurantPojo.setCid(restaurant.getCid());
		restaurantPojo.setId(restaurant.getId());
		model.addAttribute("restaurant", restaurantPojo);
	}
	
	/**
	 * 列出店铺指定菜品分类下的所有菜品
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/foods/{id}")
	public String listFoods(@PathVariable("id")int id, HttpServletRequest request)
	{
		int page = 1;
		String curPage = request.getParameter("page");
		if(!StringUtils.isEmpty(curPage)){
			page = Integer.valueOf(curPage);
		}
		long cid = LoginUtil.getCustomerId(request, customerService);
		String categoryCid = categoryService.getById(id).getCid();
		List<Category> categories = categoryService.getAllFoodCategory(categoryCid.substring(0, 4), cid);//4是第一层分类（子店铺）id的长度
		if(categoryCid.length()==4 && categories.size()!=0) {
			//长度为4表示是店铺id此处更新现在的店铺名，并传入
			request.getSession().setAttribute("currentRestaurantId", id);
			//TODO 通过读取是否允许二级目录的配置来判断
			return "redirect:/category/foods/"+categories.get(0).getId()+"?cid="+request.getAttribute("loginId");
		}
		request.setAttribute("foodCategories", categories);
		request.setAttribute("id", id);
		List<Product> foods = productService.getFoodsByCategory(id, page);
		request.setAttribute("foods", foods);
		
		List<String> productsJson = new ArrayList<String>();
		for (Product product : foods) {
			Map<String, Object> data = new HashMap<>();
			data.put("id", product.getId());
			data.put("name", product.getProductName());
			data.put("price",product.getPrice());
			data.put("number", 1);
			data.put("images", product.getImages());
			Category category = categoryService.getById(product.getCategory());
			String shopCategoryStr = null;
			if(category.getCid().length()>4) {
				shopCategoryStr = category.getCid().substring(0, 4);
			} else {
				shopCategoryStr = category.getCid();
			}
			Category shopCategory = categoryService.getByCategoryCid(shopCategoryStr, category.getCustomerId());
//			request.setAttribute("shopInfo", shopCategory.getName());
			data.put("restaurant", shopCategory.getName());
			productsJson.add(JsonUtil.parseJson(data));
		}
		
		int total = productService.getFoodsCountByCategory(id);
		if(total<=C.Paging.FRONT_PAGE_SIZE) {
			request.setAttribute("enablePage", false);
		} else {
			request.setAttribute("enablePage", true);
			if(page==1) {
				request.setAttribute("enableFirst", false);
			} else {
				request.setAttribute("enableFirst", true);
				request.setAttribute("prev", page-1);
			}
			
			int pageTotal = total % C.Paging.FRONT_PAGE_SIZE == 0 ? total / C.Paging.FRONT_PAGE_SIZE : total / C.Paging.FRONT_PAGE_SIZE + 1;
			if(page>=pageTotal) {
				request.setAttribute("enableLast", false);
			} else {
				request.setAttribute("enableLast", true);
				request.setAttribute("next", page+1);
			}
		}
		
		request.setAttribute("pjsons", productsJson);
		return "m/listFoods";
	}
}
